#!/sbin/openrc-run
# Copyright 1999-2014 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

extra_commands="cleandisk"

LOG_DIR="${LOGDIR}/${HOSTNAME}/dailylogs"

start() {
	ebegin "Starting Log_packest"
	if [ ! -x /usr/bin/snort ]
	then
		eerror "No snort - cannot start"
		eend 1
		return 1
	fi

	if [ ! -d ${LOG_DIR} ]
	then
		mkdir -p ${LOG_DIR}
		chmod 770 ${LOG_DIR}
	fi

	today=$(date '+%Y-%m-%d')

	if [ ! -d "${LOG_DIR}/${today}" ]
	then
		mkdir "${LOG_DIR}/${today}"
		chmod 770 "${LOG_DIR}/${today}"
		chown root:sguil "${LOG_DIR}/${today}"
	fi
	start-stop-daemon --start --quiet -b -m --pidfile "${PIDFILE}" \
		--exec /usr/bin/snort \
		-- ${OPTIONS} -l "${LOG_DIR}/${today}" -b -i "${IFACE}" "${FILTER}"
	real_cleandisk
	eend $?
}

stop() {
	ebegin "Stopping Sensor Agent"
	start-stop-daemon --stop --quiet --pidfile "${PIDFILE}"
	eend $?
}

cleandisk() {
	ebegin "Cleaning Disk"
	real_cleandisk
	eend $?
}

# This func checks the current space being used by LOG_DIR
# and rm's data as necessary.
real_cleandisk() {
	einfo "Checking disk space (limited to ${MAX_DISK_USE}%)..."
	# grep, awk, tr...woohoo!
	CUR_USE=$(df -P ${LOG_DIR} | grep -v -i filesystem | awk '{print $5}' | tr -d %)
	einfo "  Current Disk Use: ${CUR_USE}%"
	
	if [ ${CUR_USE} -gt ${MAX_DISK_USE} ]
	then
		# If we are here then we passed our disk limit
		# First find the oldest DIR
		cd "${LOG_DIR}"
		# Can't use -t on the ls since the mod time changes each time we
		# delete a file. Good thing we use YYYY-MM-DD so we can sort.
		OLDEST_DIR=$(ls | sort | head -n 1)
		cd "${OLDEST_DIR}"

		OLDEST_FILE=$(ls -t | tail -n 1)

		if [ -f "${OLDEST_FILE}" ]
		then
			einfo "  Removing file: ${OLDEST_DIR}/${OLDEST_FILE}"
			rm -f "${OLDEST_FILE}"
		else
			einfo "  Removing empty dir: ${OLDEST_DIR}"
			cd ..
			rm -rf "${OLDEST_DIR}"
		fi
		
		# Run cleandisk again as rm'ing one file might been enough
		# but we wait 5 secs in hopes any open writes are done.
		sync
		einfo "  Waiting 5 secs for disk to sync..."
		sleep 5
		real_cleandisk
	else
		einfo "Done."
	fi
}

